package com.ja.openchat.ui.me;

import android.os.Bundle;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.ja.openchat.R;
import com.ja.openchat.ui.base.JaBaseFragment;
import java.util.List;
import butterknife.BindView;

public abstract class AbsListFragment<T,adapter extends BaseQuickAdapter<T,BaseViewHolder>> extends JaBaseFragment implements SwipeRefreshLayout.OnRefreshListener, OnLoadMoreListener {

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.swipeRefreshLayout)
    SwipeRefreshLayout swipeRefreshLayout;
    @Override
    protected int initLayout() {
        return R.layout.fragment_record_without_layout;
    }


    @Override
    protected void initDataAndEvent(Bundle savedInstanceState) {
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mAdapter = newIntanceAdapter();

        recyclerView.setAdapter(mAdapter);
        recyclerView.setItemAnimator(null);
        mAdapter.setEmptyView(R.layout.status_center_empty_view);
        mAdapter.getLoadMoreModule().setOnLoadMoreListener(this);
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
                requestData(currentPage);
            }
        });
    }

    protected abstract adapter newIntanceAdapter();

    protected adapter mAdapter;

    @Override
    public void onRefresh() {
        currentPage = 1;
        requestData(currentPage);
    }

    @Override
    public void onLoadMore() {
        currentPage++;
        requestData(currentPage);
    }

    protected abstract void requestData(int page);

    protected final int PAGE_COUNT = 20;
    protected int currentPage = 1;

    protected void finishRefreshAndLoad(int page,List<T> objects){
        if(page == 1){
            swipeRefreshLayout.setRefreshing(false);
            mAdapter.setNewInstance(objects);
        }else{
            if(objects!=null&&objects.size()>0){
                mAdapter.addData(objects);
            }
        }
        if(objects==null||objects.size()<PAGE_COUNT){
            mAdapter.getLoadMoreModule().loadMoreEnd(true);
        }else{
            mAdapter.getLoadMoreModule().loadMoreComplete();
        }
    }
}
